package yo.latyoo.hokage.skmr.biz.repository;

import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import yo.latyoo.hokage.skmr.biz.domain.JobInfo;
import yo.latyoo.hokage.skmr.biz.model.JobModel;

import java.time.LocalDateTime;
import java.util.List;

public interface JobInfoRepo extends JpaSpecificationExecutor<JobInfo>, JpaRepository<JobInfo, Long> {

    List<JobInfo> findByJobStatusAndNextRunTimeLessThanEqual(int status, LocalDateTime time);


    @Query(
            value = """
                    select new  yo.latyoo.hokage.skmr.biz.model.JobModel( ji.id,jg.registryList,  ji.jobDesc,  ji.scheduleType,  ji.expression, 
                     ji.handlerMethod,  ji.handlerParams,  ji.timeout,  ji.failRetryCount, 
                     ji.routeType,  ji.shardingIndex,  ji.nextRunTime,ji.lastRunTime) 
                    from JobInfo ji inner join JobGroup jg on jg.id = ji.groupId
                    where ji.jobStatus = 1 and ji.nextRunTime <= ?1
                    """
             )
    List<JobModel> findByNextRunTime(LocalDateTime time);

    @Transactional
    @Modifying
    @Query("update JobInfo set nextRunTime = ?2,lastRunTime = ?3,updatedAt = ?4 where id = ?1")
    void updateNextRunTime(Long id,LocalDateTime nextRunTime,LocalDateTime lastRunTime,LocalDateTime updatedAt);

}
